package com.zzw.mode;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

/**
 * @author zzw
 * @see
 * @since 2018/3/7
 */
public abstract class QueryTemplate<T> {
    private static final String URL="jdbc:mysql://localhost:3306/db2?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8";

    private static final String USER="root";

    private static final String PASSWORD="root";

    protected Connection getConnection(){
        try{
            return DriverManager.getConnection(URL,USER,PASSWORD);
        }catch (Exception e){
            throw  new RuntimeException("Get connection error.",e);
        }
    }


    protected Statement createStatement(Connection connection){
        try {
            return  connection.createStatement();
        }catch (Exception e){
            throw new RuntimeException("Create statement error.",e);
        }
    }

    protected ResultSet executeQuery(Statement statement, String sql){
        try {
            return statement.executeQuery(sql);
        }catch (Exception e){
            throw new RuntimeException("Execute query error.",e);
        }

    }

    protected void cleanResource(ResultSet resultSet,Statement statement,Connection connection){
        try {
            if(resultSet!=null){
                resultSet.close();
            }

            if(statement!=null){
                statement.close();
            }

            if(connection!=null){
                connection.close();
            }
        }catch (Exception e){
            throw new RuntimeException("Clear resource error.",e);
        }
    }

    public T query(final String sql){
        Connection connection=null;
        Statement statement=null;
        ResultSet resultSet=null;
        try {
            connection = getConnection();
            statement = createStatement(connection);
            resultSet = executeQuery(statement, sql);
            return resolveResultSet(resultSet);
        }finally {
            cleanResource(resultSet,statement,connection);
        }

    }

    protected abstract T  resolveResultSet(ResultSet resultSet);
}
